package com.github.hongkaiwen.rxjava.play;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;

/**
 * 密级别：classify:p2#- User: hongkai Date: 15/08/2018 9:59 AM Description:
 */
public class RXHttpUtil {


    public static Observable<HttpResponse> get(String url) {
        return Observable.create((ObservableOnSubscribe) emitter -> {
            HttpGet request = new HttpGet(url);
            FutureCallback<HttpResponse> callback = new FutureCallback<HttpResponse>() {
                @Override
                public void completed(HttpResponse httpResponse) {
                    emitter.onNext(httpResponse);
                }

                @Override
                public void failed(Exception e) {
                    emitter.onError(e);
                }

                @Override
                public void cancelled() {
                    // i don't know what to do
                }
            };
            RXHttpUtil.httpclient.execute(request, callback);
        });

    }

    public static Observable<String> getBody(String url){
        return get(url).map(t -> EntityUtils.toString(t.getEntity()));
    }

    private static CloseableHttpAsyncClient httpclient;

    static {
        httpclient = HttpAsyncClients.createDefault();
        httpclient.start();
        Runtime.getRuntime().addShutdownHook(new Thread(() -> close()));
    }

    private static void close() {
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
